package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zong-microservice/app/models"
	"zong-microservice/app/services/apigw/handlers"
	request "zong-microservice/app/services/apigw/http/requests"
	"zong-microservice/pkg/response"
)

type AuthController struct {
	loginRequest request.AuthLoginRequest
	//logoutRequest request.AuthLogoutRequest
	userModel models.User
	client    handlers.AuthHandler
}

// Options
func (authController *AuthController) Options(context *gin.Context) {
	context.JSON(http.StatusOK, "Options Request!")
}

// Login 用户登录
func (authController *AuthController) Login(context *gin.Context) {
	if err := context.ShouldBindJSON(&authController.loginRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	if result, err := authController.client.RpcLogin(authController.loginRequest); err != nil {
		response.ResponseServerError(context, err.Error())
		return
	} else {
		response.ResponseAuto(context, result.Code, result.Message, result.Data)
		return
	}
}

// Logout 用户退出
func (authController *AuthController) Logout(context *gin.Context) {
	//if err := context.ShouldBindJSON(&authController.logoutRequest); err != nil {
	//	response.ResponseBadRequest(context)
	//	return
	//}

	// 删除 token 实际是刷新 token 但是不返回
	authorization := context.Request.Header.Get("Authorization")

	if result, err := authController.client.RpcLogout(authorization); err != nil {
		response.ResponseServerError(context, err.Error())
		return
	} else {
		response.ResponseAuto(context, result.Code, result.Message, nil)
		return
	}
}

// Refresh 用户刷新token
func (authController *AuthController) Refresh(context *gin.Context) {
	authorization := context.Request.Header.Get("Authorization")

	if result, err := authController.client.RpcRefresh(authorization); err != nil {
		response.ResponseServerError(context, err.Error())
		return
	} else {
		response.ResponseAuto(context, result.Code, result.Message, result.Data)
		return
	}
}
